package com.nbjtjc.safe.service.sys;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbjtjc.safe.bean.Constant;
import com.nbjtjc.safe.bean.Page;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.sys.SysDeptMapper;
import com.nbjtjc.safe.mapper.sys.SysUserMapper;
import com.nbjtjc.safe.mapper.sys.SysUserRoleMapper;
import com.nbjtjc.safe.model.edu.EduCertificate;
import com.nbjtjc.safe.model.sys.SysDept;
import com.nbjtjc.safe.model.sys.SysNotice;
import com.nbjtjc.safe.model.sys.SysUser;
import com.nbjtjc.safe.model.sys.SysUserRole;
import com.nbjtjc.safe.util.FileUtil;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.apache.catalina.security.SecurityUtil;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

@Service
public class SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private FileUtil fileUtil;
    @Autowired
    private SysNoticeService sysNoticeService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Value("${wx.APP_SECRET}")
    private String APP_SECRET;
    @Value("${wx.APP_ID}")
    private String APP_ID;

    @Value("${file.path.tempPath}")
    private String fileTempPath;

    @Autowired
    private SysUserRoleMapper userRoleMapper;
    public Result find(SysUser user, Page page) {
        Result result = new Result();
        PageHelper.startPage(page.getPageCurrent(), page.getPageSize());
        List<SysUser> sysUsers = sysUserMapper.search(user, page);
        if (CollectionUtil.isNotEmpty(sysUsers)) {
            for (int i = 0; i < sysUsers.size(); i++) {
                sysUsers.get(i).setNum(i + 1);
            }
        }

        result.setData(new PageInfo<>(sysUsers));
        return result;
    }

    public Result addOrUpdate(SysUser user) {
        Result result = new Result();
        if (ObjectUtil.isNull(user)) {
            result.setFalse("不能为空");
            return result;
        }
        int res = 0;
        if (ObjectUtil.isNull(user.getUserId())) {
            user.setCreateTime(new Date());
            user.setPassword(SecureUtil.md5(user.getPassword()));
            res = sysUserMapper.insertSelective(user);
        } else {
            if (StringUtils.isNotEmpty(user.getLoginName())) {
                //判断登录名是否重复
                SysUser searchParam = new SysUser();
                searchParam.setLoginName(user.getLoginName());
                List<SysUser> sysUsers = sysUserMapper.select(searchParam);
                if (CollectionUtil.isNotEmpty(sysUsers)) {
                    for (int i = 0; i < sysUsers.size(); i++) {
                        if (!sysUsers.get(i).getUserId().equals(user.getUserId())) {
                            result.setFalse("用户名重复");
                            return result;
                        }
                    }
                }
            }

            if (ObjectUtil.isNotNull(user.getPassword())) {
                user.setPassword(SecureUtil.md5(user.getPassword()));
            }
            //判断是否要转岗培训并通知
            SysUser sysUserDataBase = sysUserMapper.selectByPrimaryKey(user.getUserId());
            String reassignFlagDataBase = sysUserDataBase.getReassignFlag();
            String reassignFlagInput = user.getReassignFlag();
            boolean reassignFlagDataBaseFlag = ObjectUtil.isNull(reassignFlagDataBase)
                    || (ObjectUtil.isNotNull(reassignFlagDataBase)
                    && (reassignFlagDataBase == ""
                    || reassignFlagDataBase == "0"
                    || reassignFlagDataBase == "否"
                    || reassignFlagDataBase == "无"));
            boolean reassignInputFlag = ObjectUtil.isNull(reassignFlagInput)
                    || (ObjectUtil.isNotNull(reassignFlagInput)
                    && (reassignFlagInput == ""
                    || reassignFlagInput == "0"
                    || reassignFlagInput == "否"
                    || reassignFlagInput == "无"));

            //更新人员信息
            res = sysUserMapper.updateByPrimaryKeySelective(user);

            //通知转岗培训
            if (reassignFlagDataBaseFlag = true && reassignInputFlag == false) {
                SysNotice sysNotice = new SysNotice();
                sysNotice.setContent("由于岗位调整，需对" + sysUserDataBase.getUsername() + "进行转岗培训");
                sysNotice.setCompanyId(MyShiroUtils.getCompanyId());
                sysNotice.setWriteUserId(MyShiroUtils.getSessionUser().getUserId());
                sysNotice.setDeptId(MyShiroUtils.getDeptId());
                sysNotice.setCreateTime(new Date());
                sysNotice.setIdType(7);
                sysNotice.setRelateId(user.getUserId());
                sysNotice.setNoticeType(0);
                sysNotice.setNoticeStatus(Constant.SysNoticeStatus.PUBLIC.getValue());
                sysNotice.setTitle("需对" + sysUserDataBase.getUsername() + "进行转岗培训");
                List<Integer> users = new ArrayList();
                users.add(MyShiroUtils.getSessionUserId());
                boolean f = sysNoticeService.addNoticeList(sysNotice, users);
                if (!f) {
                    result.setFalse("通知发送失败");
                }
            }
        }
        if (res == 0) {
            result.setFalse("插入或者更新失败");
        }
        result.setData(user);
        return result;
    }

    //导入人员花名册
    @Transactional(rollbackFor = {Throwable.class})
    public Result addBatch(MultipartFile multipartFile) throws IOException, ParseException {
        Result result = new Result();

        String fileName = multipartFile.getOriginalFilename();
        File targetFile = new File(fileUtil.getFilePath() + multipartFile.getOriginalFilename());
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }
        multipartFile.transferTo(targetFile);
        if (fileName.endsWith("xls")) {
            result = readXls(targetFile);
        } else if (fileName.endsWith("xlsx")) {
            result = readXlsx(targetFile);
        } else {
            result.setFalse("传入文件不是excel表格，请检查");
            return result;
        }
        return result;
    }

    //导入xls
    public Result readXls(File excelFile) throws IOException, ParseException {
        Result result = new Result();

        InputStream is = new FileInputStream(excelFile);
        // HSSFWorkbook 标识整个excel
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);

        HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);

        List<SysUser> insertSysUsers = new ArrayList();
        List<SysUser> updateSysUsers = new ArrayList();
        //获取excel表中数据
        int lastRowNum = hssfSheet.getLastRowNum();
        int firstRowNum = hssfSheet.getFirstRowNum();
        for (int rowNum = 2; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
            // HSSFRow表示行
            HSSFRow hssfRow = hssfSheet.getRow(rowNum);

            if (ObjectUtil.isNull(hssfRow)) {
                break;
            }
            //身份证号单元格不能 为空
            Cell cell = hssfRow.getCell(0);
            if (ObjectUtil.isNull(cell)) {
                break;
            }

            //身份证号单元格取值不能为空
            String content1 = hssfRow.getCell(0).getStringCellValue();
            if (ObjectUtil.isNull(content1) || content1 == "") {
                break;
            }
            SysUser sysUser = new SysUser();
//            int minColIx = hssfRow.getFirstCellNum();
//            int maxColIx = hssfRow.getLastCellNum();
            //为空则结束导入
            String idNumber = hssfRow.getCell(0).getStringCellValue().trim();
            if (ObjectUtil.isNull(idNumber) || idNumber == "") {
                break;
            }
//            //不为18位则跳过该人，进行下一人
//            if(idNumber.length()!=18){
//            	continue;
//            }
            sysUser.setIdNumber(idNumber);
            List<SysUser> userTemps = sysUserMapper.select(sysUser);
            if (CollectionUtil.isNotEmpty(userTemps)) {
                //按身份证查找，已有的为更新人员信息
                sysUser = userTemps.get(0);
                sysUser = inputTableValue(sysUser, hssfRow);
                updateSysUsers.add(sysUser);
            } else {
                //按身份证查找，没有的为新增人员信息
                sysUser = inputTableValue(sysUser, hssfRow);
                insertSysUsers.add(sysUser);
            }
        }

        for (SysUser sysUser : updateSysUsers) {
            int res = sysUserMapper.updateByPrimaryKeySelective(sysUser);
            if (res == 0) {
                result.setFalse("更新数据失败，失败处的身份证号为：" + sysUser.getIdNumber() + ",对应用户id为" + sysUser.getUserId());
                return result;
            }
        }
        if (CollectionUtil.isNotEmpty(insertSysUsers)) {
            for (int i = 0; i < insertSysUsers.size(); i++) {
                int res = sysUserMapper.insertSelective(insertSysUsers.get(i));
                if (res == 0) {
                    result.setFalse("添加数据失败");
                    return result;
                }

                int[] roleIds = {32};

                if (ObjectUtil.isNotNull(insertSysUsers.get(i).getUserId())) {
                    result = sysUserRoleService.add(roleIds, insertSysUsers.get(i).getUserId());
                }
            }
        }
//        if(CollectionUtil.isNotEmpty(insertSysUsers)){
//            int res = sysUserMapper.insertList(insertSysUsers);
//            if(res == 0){
//            	result.setFalse("添加数据失败");
//                return result;
//            }
//            
//            for(int i=0;i<insertSysUsers.size();i++){
//            	int[] roleIds= {32};
//            	List<SysUser> sysUsers= sysUserMapper.search(insertSysUsers.get(i),new Page());
//            	if(CollectionUtil.isNotEmpty(sysUsers)){
//            		insertSysUsers.set(i,sysUsers.get(0));
//            	}
//            	if(ObjectUtil.isNotNull(insertSysUsers.get(i).getUserId())){
//               	 result = sysUserRoleService.add(roleIds, insertSysUsers.get(i).getUserId());
//            	}
//            }
//        }


        insertSysUsers.addAll(updateSysUsers);

        result.setData(insertSysUsers);

        return result;
    }

    //导入xlsx
    public Result readXlsx(File excelFile) throws IOException, ParseException {
        Result result = new Result();

        InputStream is = new FileInputStream(excelFile);
        // XSSFWorkbook 标识整个excel
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);

        XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);

        List<SysUser> insertSysUsers = new ArrayList();
        List<SysUser> updateSysUsers = new ArrayList();
        //获取excel表中数据
        int lastRowNum = xssfSheet.getLastRowNum();
        int firstRowNum = xssfSheet.getFirstRowNum();
        for (int rowNum = 2; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
            // XSSFRow表示行
            XSSFRow xssfRow = xssfSheet.getRow(rowNum);

            if (ObjectUtil.isNull(xssfRow)) {
                break;
            }
            //身份证号单元格不能 为空
            Cell cell = xssfRow.getCell(0);
            if (ObjectUtil.isNull(cell)) {
                break;
            }

            //身份证号单元格取值不能为空
            String content1 = xssfRow.getCell(0).getStringCellValue();
            if (ObjectUtil.isNull(content1) || content1 == "") {
                break;
            }
            SysUser sysUser = new SysUser();
//            int minColIx = xssfRow.getFirstCellNum();
//            int maxColIx = xssfRow.getLastCellNum();
            //为空则结束导入
            String idNumber = xssfRow.getCell(0).getStringCellValue().trim();
            if (ObjectUtil.isNull(idNumber) || idNumber == "") {
                break;
            }
//            //不为18位则跳过该人，进行下一人
//            if(idNumber.length()!=18){
//            	continue;
//            }
            sysUser.setIdNumber(idNumber);
            List<SysUser> userTemps = sysUserMapper.select(sysUser);
            if (CollectionUtil.isNotEmpty(userTemps)) {
                //按身份证查找，已有的为更新人员信息
                sysUser = userTemps.get(0);
                sysUser = inputTableValue(sysUser, xssfRow);
                updateSysUsers.add(sysUser);
            } else {
                //按身份证查找，没有的为新增人员信息
                sysUser = inputTableValue(sysUser, xssfRow);
                insertSysUsers.add(sysUser);
            }
        }

        for (SysUser sysUser : updateSysUsers) {
            int res = sysUserMapper.updateByPrimaryKeySelective(sysUser);
            if (res == 0) {
                result.setFalse("更新数据失败，失败处的身份证号为：" + sysUser.getIdNumber() + ",对应用户id为" + sysUser.getUserId());
                return result;
            }
        }
        if (CollectionUtil.isNotEmpty(insertSysUsers)) {
            for (int i = 0; i < insertSysUsers.size(); i++) {
                int res = sysUserMapper.insertSelective(insertSysUsers.get(i));
                if (res == 0) {
                    result.setFalse("添加数据失败");
                    return result;
                }

                int[] roleIds = {32};

                if (ObjectUtil.isNotNull(insertSysUsers.get(i).getUserId())) {
                    result = sysUserRoleService.add(roleIds, insertSysUsers.get(i).getUserId());
                }
            }
        }
//        if(CollectionUtil.isNotEmpty(insertSysUsers)){
//            int res = sysUserMapper.insertList(insertSysUsers);
//            if(res == 0){
//            	result.setFalse("添加数据失败");
//                return result;
//            }
//            
//            for(int i=0;i<insertSysUsers.size();i++){
//            	int[] roleIds= {32};
//            	List<SysUser> sysUsers= sysUserMapper.search(insertSysUsers.get(i),new Page());
//            	if(CollectionUtil.isNotEmpty(sysUsers)){
//            		insertSysUsers.set(i,sysUsers.get(0));
//            	}
//            	if(ObjectUtil.isNotNull(insertSysUsers.get(i).getUserId())){
//               	 result = sysUserRoleService.add(roleIds, insertSysUsers.get(i).getUserId());
//            	}
//            }
//        }


        insertSysUsers.addAll(updateSysUsers);

        result.setData(insertSysUsers);

        return result;
    }

    public SysUser inputTableValue(SysUser sysUser, XSSFRow xssfRow) throws ParseException {
        //身份证号
        String idNumber = xssfRow.getCell(0).getStringCellValue().trim();
        sysUser.setIdNumber(idNumber);
        String birthday = idNumber.substring(6, 14);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        sysUser.setBirthday(sdf.parse(birthday));
        //姓名
        String userName = null;
        if (ObjectUtil.isNotNull(xssfRow.getCell(1))) {
            userName = xssfRow.getCell(1).getStringCellValue();
            if (ObjectUtil.isNotNull(userName)) {
                sysUser.setUsername(userName);
            }
        }


        //性别
        if (ObjectUtil.isNotNull(xssfRow.getCell(2))) {
            if (xssfRow.getCell(2).getStringCellValue().equals("男")) {
                sysUser.setGender(true);
            } else if (xssfRow.getCell(2).getStringCellValue().equals("女")) {
                sysUser.setGender(false);
            }
        }


        //联系电话
        if (ObjectUtil.isNotNull(xssfRow.getCell(3))) {
//            int cellType = xssfRow.getCell(3).getCellType();
//            int cellNumType = XSSFCell.CELL_TYPE_NUMERIC;
//            int cellStringType = XSSFCell.CELL_TYPE_NUMERIC;
//
//            if (xssfRow.getCell(3).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
//                Double mobile = xssfRow.getCell(3).getNumericCellValue();
//                Long intmobile = mobile.longValue();
//                sysUser.setMobile(intmobile.toString());
//            } else if (xssfRow.getCell(3).getCellType() == XSSFCell.CELL_TYPE_STRING) {
//                sysUser.setMobile(xssfRow.getCell(3).getStringCellValue());
//            }
        }

//    	if(ObjectUtil.isNotNull(xssfRow.getCell(3))){
//        	sysUser.setMobile(xssfRow.getCell(3).getStringCellValue());
//    	}

        //学历
        if (ObjectUtil.isNotNull(xssfRow.getCell(4))) {
            sysUser.setDegreeOfEducation(xssfRow.getCell(4).getStringCellValue());
        }
        //人员归属
        if (ObjectUtil.isNotNull(xssfRow.getCell(5))) {
            if (xssfRow.getCell(5).getStringCellValue().equals("公司员工")) {
                sysUser.setTemp(true);
            } else if (xssfRow.getCell(5).getStringCellValue().equals("劳务派遣")) {
                sysUser.setTemp(false);
            }
        }


        //在职单位
        if (ObjectUtil.isNotNull(xssfRow.getCell(6))) {
            String comName = xssfRow.getCell(6).getStringCellValue().trim();
            SysDept sysDeptTemp = new SysDept();
            sysDeptTemp.setName(comName);
            sysDeptTemp.setType(1);
//        	List<SysDept>	sysDepts =sysDeptMapper.select(sysDeptTemp);
            List<SysDept> sysDepts = new ArrayList();
            sysDepts.addAll(sysDeptMapper.select(sysDeptTemp));

            if (CollectionUtil.isNotEmpty(sysDepts)) {
                //公司名存在则用数据库中公司ID
                int comId = sysDepts.get(0).getId();
                sysUser.setCompanyId(comId);

                //在职部门
                //获取部门名称
                String deptName;
                if (ObjectUtil.isNotNull(xssfRow.getCell(7))) {
                    deptName = xssfRow.getCell(7).getStringCellValue().trim();
                } else {
                    deptName = "";

                }
//            	if(ObjectUtil.isNotNull(deptName)){
//            		
//            	}
                sysDeptTemp.setName(deptName);
                sysDeptTemp.setType(0);
                sysDepts.clear();
                //按部门名称搜索部门对象
                sysDepts.addAll(sysDeptMapper.select(sysDeptTemp));
                //结果不为空则继续，为空则不操作
                if (CollectionUtil.isNotEmpty(sysDepts)) {

                    for (SysDept dept : sysDepts) {
                        //结果需得是该公司下属的部门
                        if (comId == sysDeptService.getFatherCompanyId(dept.getId())) {
                            sysUser.setDeptId((long) dept.getId());
                            break;
                        }
                    }
                }
            }//公司名不存在则不操作，不赋值
        }


        //在职岗位
        if (ObjectUtil.isNotNull(xssfRow.getCell(8)) && ObjectUtil.isNotNull(xssfRow.getCell(8).getStringCellValue())) {
            sysUser.setDuty(xssfRow.getCell(8).getStringCellValue());
        }

        //入职时间
        String dateString1 = "";
//        if (ObjectUtil.isNotNull(xssfRow.getCell(9))) {
//            if (xssfRow.getCell(9).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
//                if (ObjectUtil.isNotNull(xssfRow.getCell(9).getDateCellValue())) {
//                    sysUser.setEntryDate(xssfRow.getCell(9).getDateCellValue());
//                }
//            } else if (xssfRow.getCell(9).getCellType() == XSSFCell.CELL_TYPE_STRING) {
//                dateString1 = xssfRow.getCell(9).getStringCellValue();
//                if (ObjectUtil.isNotNull(dateString1) && dateString1 != "" && dateString1.trim() != "") {
//                    sysUser.setEntryDate(formateDate(dateString1));
//                }
//            }
//        }

//    	String dateString1 = xssfRow.getCell(9).getStringCellValue().trim();
//    	if(ObjectUtil.isNotNull(xssfRow.getCell(9))&&ObjectUtil.isNotNull(dateString1)&&dateString1!=""){
//    		
//        	sysUser.setEntryDate(formateDate(dateString1));
//
//
//    	}


        //三级安全教育
        String entryTrain = null;
        if (ObjectUtil.isNotNull(xssfRow.getCell(10))) {
            entryTrain = xssfRow.getCell(10).getStringCellValue();
            if (entryTrain.equals("是")) {
                sysUser.setEntryTrain(true);
            } else if (entryTrain.equals("否")) {
                sysUser.setEntryTrain(false);
            }
        }


        //岗位调整
        if (ObjectUtil.isNotNull(xssfRow.getCell(11)) && ObjectUtil.isNotNull(xssfRow.getCell(11).getStringCellValue())) {
            sysUser.setReassignFlag(xssfRow.getCell(11).getStringCellValue());
        }

        //岗位调整时间
        String dateString2 = "";
//        if (ObjectUtil.isNotNull(xssfRow.getCell(12))) {
//            if (xssfRow.getCell(12).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
//                if (ObjectUtil.isNotNull(xssfRow.getCell(12).getDateCellValue())) {
//                    sysUser.setEntryDate(xssfRow.getCell(12).getDateCellValue());
//                }
//            } else if (xssfRow.getCell(12).getCellType() == XSSFCell.CELL_TYPE_STRING) {
//                dateString2 = xssfRow.getCell(12).getStringCellValue();
//                if (ObjectUtil.isNotNull(dateString2) && dateString2 != "" && dateString2.trim() != "") {
//                    sysUser.setEntryDate(formateDate(dateString2));
//                }
//            }
//        }

//    	String dateString2 ="";
//    	if(ObjectUtil.isNotNull(xssfRow.getCell(12))){
//        	dateString2 = xssfRow.getCell(12).getStringCellValue();
//        	if(ObjectUtil.isNotNull(dateString2)&&dateString2!=""){
//        		sysUser.setReassignDate(formateDate(dateString2));
//        	}
//    	}


        //调、脱岗安全教育
        String reassignTrain = null;
        if (ObjectUtil.isNotNull(xssfRow.getCell(13))) {
            reassignTrain = xssfRow.getCell(13).getStringCellValue();

            if (reassignTrain.equals("是")) {
                sysUser.setReassignTrain(true);
            } else if (reassignTrain.equals("否")) {
                sysUser.setReassignTrain(false);
            } else {
                sysUser.setReassignTrain(false);
            }
        }
        //离职
        if (ObjectUtil.isNotNull(xssfRow.getCell(14)) && ObjectUtil.isNotNull(xssfRow.getCell(14).getStringCellValue())) {
            sysUser.setLeaveFlag(xssfRow.getCell(14).getStringCellValue());
        }

        //离职时间

        String dateString3 = "";
        if (ObjectUtil.isNotNull(xssfRow.getCell(15))) {
//            if (xssfRow.getCell(15).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
//                if (ObjectUtil.isNotNull(xssfRow.getCell(15).getDateCellValue())) {
//                    sysUser.setEntryDate(xssfRow.getCell(15).getDateCellValue());
//                }
//            } else if (xssfRow.getCell(15).getCellType() == XSSFCell.CELL_TYPE_STRING) {
//                dateString3 = xssfRow.getCell(15).getStringCellValue();
//                if (ObjectUtil.isNotNull(dateString3) && dateString3 != "" && dateString3.trim() != "") {
//                    sysUser.setEntryDate(formateDate(dateString3));
//                }
//            }
        }

//    	String dateString3 = null;
//    	if(ObjectUtil.isNotNull(xssfRow.getCell(15))){
//        	dateString3 = xssfRow.getCell(15).getStringCellValue();
//    	}
//    	if(ObjectUtil.isNotNull(dateString3)&&dateString3!=""){
//    		sysUser.setReassignDate(formateDate(dateString3));
//    	}

        //现入职单位
        if (ObjectUtil.isNotNull(xssfRow.getCell(16)) && ObjectUtil.isNotNull(xssfRow.getCell(16).getStringCellValue())) {
            sysUser.setCurrentComp(xssfRow.getCell(16).getStringCellValue());
        }

        //status
        sysUser.setStatus((byte) 0);
        //是公司员工就创建登录名和密码
        if (ObjectUtil.isNotNull(xssfRow.getCell(5)) && ObjectUtil.isNotNull(xssfRow.getCell(5).getStringCellValue())
                && xssfRow.getCell(5).getStringCellValue().equals("公司员工")) {
            String idLast = idNumber.substring(14);
            String loginName = userName + idLast;
            sysUser.setLoginName(loginName);
            //初始化密码
            sysUser.setPassword(SecureUtil.md5("123456"));
        }

        //记录创建时间
        sysUser.setCreateTime(new Date());

        return sysUser;
    }


    public SysUser inputTableValue(SysUser sysUser, HSSFRow hssfRow) throws ParseException {
        //身份证号
        String idNumber = hssfRow.getCell(0).getStringCellValue().trim();
        sysUser.setIdNumber(idNumber);
        String birthday = idNumber.substring(6, 14);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        sysUser.setBirthday(sdf.parse(birthday));
        //姓名
        String userName = null;
        if (ObjectUtil.isNotNull(hssfRow.getCell(1))) {
            userName = hssfRow.getCell(1).getStringCellValue();
            if (ObjectUtil.isNotNull(userName)) {
                sysUser.setUsername(userName);
            }
        }


        //性别
        if (ObjectUtil.isNotNull(hssfRow.getCell(2))) {
            if (hssfRow.getCell(2).getStringCellValue().equals("男")) {
                sysUser.setGender(true);
            } else if (hssfRow.getCell(2).getStringCellValue().equals("女")) {
                sysUser.setGender(false);
            }
        }


        //联系电话
        if (ObjectUtil.isNotNull(hssfRow.getCell(3))) {
//            int cellType = hssfRow.getCell(3).getCellType();
//            int cellNumType = HSSFCell.CELL_TYPE_NUMERIC;
//            int cellStringType = HSSFCell.CELL_TYPE_NUMERIC;
//
//            if (hssfRow.getCell(3).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
//                Double mobile = hssfRow.getCell(3).getNumericCellValue();
//                Long intmobile = mobile.longValue();
//                sysUser.setMobile(intmobile.toString());
//            } else if (hssfRow.getCell(3).getCellType() == HSSFCell.CELL_TYPE_STRING) {
//                sysUser.setMobile(hssfRow.getCell(3).getStringCellValue());
//            }
        }

//    	if(ObjectUtil.isNotNull(hssfRow.getCell(3))){
//        	sysUser.setMobile(hssfRow.getCell(3).getStringCellValue());
//    	}

        //学历
        if (ObjectUtil.isNotNull(hssfRow.getCell(4))) {
            sysUser.setDegreeOfEducation(hssfRow.getCell(4).getStringCellValue());
        }
        //人员归属
        if (ObjectUtil.isNotNull(hssfRow.getCell(5))) {
            if (hssfRow.getCell(5).getStringCellValue().equals("公司员工")) {
                sysUser.setTemp(true);
            } else if (hssfRow.getCell(5).getStringCellValue().equals("劳务派遣")) {
                sysUser.setTemp(false);
            }
        }


        //在职单位
        if (ObjectUtil.isNotNull(hssfRow.getCell(6))) {
            String comName = hssfRow.getCell(6).getStringCellValue().trim();
            SysDept sysDeptTemp = new SysDept();
            sysDeptTemp.setName(comName);
            sysDeptTemp.setType(1);
//        	List<SysDept>	sysDepts =sysDeptMapper.select(sysDeptTemp);
            List<SysDept> sysDepts = new ArrayList();
            sysDepts.addAll(sysDeptMapper.select(sysDeptTemp));

            if (CollectionUtil.isNotEmpty(sysDepts)) {
                //公司名存在则用数据库中公司ID
                int comId = sysDepts.get(0).getId();
                sysUser.setCompanyId(comId);

                //在职部门
                //获取部门名称
                String deptName;
                if (ObjectUtil.isNotNull(hssfRow.getCell(7))) {
                    deptName = hssfRow.getCell(7).getStringCellValue().trim();
                } else {
                    deptName = "";

                }
//            	if(ObjectUtil.isNotNull(deptName)){
//            		
//            	}
                sysDeptTemp.setName(deptName);
                sysDeptTemp.setType(0);
                sysDepts.clear();
                //按部门名称搜索部门对象
                sysDepts.addAll(sysDeptMapper.select(sysDeptTemp));
                //结果不为空则继续，为空则不操作
                if (CollectionUtil.isNotEmpty(sysDepts)) {

                    for (SysDept dept : sysDepts) {
                        //结果需得是该公司下属的部门
                        if (comId == sysDeptService.getFatherCompanyId(dept.getId())) {
                            sysUser.setDeptId((long) dept.getId());
                            break;
                        }
                    }
                }
            }//公司名不存在则不操作，不赋值
        }


        //在职岗位
        if (ObjectUtil.isNotNull(hssfRow.getCell(8)) && ObjectUtil.isNotNull(hssfRow.getCell(8).getStringCellValue())) {
            sysUser.setDuty(hssfRow.getCell(8).getStringCellValue());
        }

        //入职时间
        String dateString1 = "";
        if (ObjectUtil.isNotNull(hssfRow.getCell(9))) {
//            if (hssfRow.getCell(9).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
//                if (ObjectUtil.isNotNull(hssfRow.getCell(9).getDateCellValue())) {
//                    sysUser.setEntryDate(hssfRow.getCell(9).getDateCellValue());
//                }
//            } else if (hssfRow.getCell(9).getCellType() == HSSFCell.CELL_TYPE_STRING) {
//                dateString1 = hssfRow.getCell(9).getStringCellValue();
//                if (ObjectUtil.isNotNull(dateString1) && dateString1 != "" && dateString1.trim() != "") {
//                    sysUser.setEntryDate(formateDate(dateString1));
//                }
//            }
        }

//    	String dateString1 = hssfRow.getCell(9).getStringCellValue().trim();
//    	if(ObjectUtil.isNotNull(hssfRow.getCell(9))&&ObjectUtil.isNotNull(dateString1)&&dateString1!=""){
//    		
//        	sysUser.setEntryDate(formateDate(dateString1));
//
//
//    	}


        //三级安全教育
        String entryTrain = null;
        if (ObjectUtil.isNotNull(hssfRow.getCell(10))) {
            entryTrain = hssfRow.getCell(10).getStringCellValue();
            if (entryTrain.equals("是")) {
                sysUser.setEntryTrain(true);
            } else if (entryTrain.equals("否")) {
                sysUser.setEntryTrain(false);
            }
        }


        //岗位调整
        if (ObjectUtil.isNotNull(hssfRow.getCell(11)) && ObjectUtil.isNotNull(hssfRow.getCell(11).getStringCellValue())) {
            sysUser.setReassignFlag(hssfRow.getCell(11).getStringCellValue());
        }

        //岗位调整时间
        String dateString2 = "";
        if (ObjectUtil.isNotNull(hssfRow.getCell(12))) {
//            if (hssfRow.getCell(12).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
//                if (ObjectUtil.isNotNull(hssfRow.getCell(12).getDateCellValue())) {
//                    sysUser.setEntryDate(hssfRow.getCell(12).getDateCellValue());
//                }
//            } else if (hssfRow.getCell(12).getCellType() == HSSFCell.CELL_TYPE_STRING) {
//                dateString2 = hssfRow.getCell(12).getStringCellValue();
//                if (ObjectUtil.isNotNull(dateString2) && dateString2 != "" && dateString2.trim() != "") {
//                    sysUser.setEntryDate(formateDate(dateString2));
//                }
//            }
        }

//    	String dateString2 ="";
//    	if(ObjectUtil.isNotNull(hssfRow.getCell(12))){
//        	dateString2 = hssfRow.getCell(12).getStringCellValue();
//        	if(ObjectUtil.isNotNull(dateString2)&&dateString2!=""){
//        		sysUser.setReassignDate(formateDate(dateString2));
//        	}
//    	}


        //调、脱岗安全教育
        String reassignTrain = null;
        if (ObjectUtil.isNotNull(hssfRow.getCell(13))) {
            reassignTrain = hssfRow.getCell(13).getStringCellValue();

            if (reassignTrain.equals("是")) {
                sysUser.setReassignTrain(true);
            } else if (reassignTrain.equals("否")) {
                sysUser.setReassignTrain(false);
            } else {
                sysUser.setReassignTrain(false);
            }
        }
        //离职
        if (ObjectUtil.isNotNull(hssfRow.getCell(14)) && ObjectUtil.isNotNull(hssfRow.getCell(14).getStringCellValue())) {
            sysUser.setLeaveFlag(hssfRow.getCell(14).getStringCellValue());
        }

        //离职时间

        String dateString3 = "";
        if (ObjectUtil.isNotNull(hssfRow.getCell(15))) {
//            if (hssfRow.getCell(15).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
//                if (ObjectUtil.isNotNull(hssfRow.getCell(15).getDateCellValue())) {
//                    sysUser.setEntryDate(hssfRow.getCell(15).getDateCellValue());
//                }
//            } else if (hssfRow.getCell(15).getCellType() == HSSFCell.CELL_TYPE_STRING) {
//                dateString3 = hssfRow.getCell(15).getStringCellValue();
//                if (ObjectUtil.isNotNull(dateString3) && dateString3 != "" && dateString3.trim() != "") {
//                    sysUser.setEntryDate(formateDate(dateString3));
//                }
//            }
        }

//    	String dateString3 = null;
//    	if(ObjectUtil.isNotNull(hssfRow.getCell(15))){
//        	dateString3 = hssfRow.getCell(15).getStringCellValue();
//    	}
//    	if(ObjectUtil.isNotNull(dateString3)&&dateString3!=""){
//    		sysUser.setReassignDate(formateDate(dateString3));
//    	}

        //现入职单位
        if (ObjectUtil.isNotNull(hssfRow.getCell(16)) && ObjectUtil.isNotNull(hssfRow.getCell(16).getStringCellValue())) {
            sysUser.setCurrentComp(hssfRow.getCell(16).getStringCellValue());
        }

        //status
        sysUser.setStatus((byte) 0);
        //是公司员工就创建登录名和密码
        if (ObjectUtil.isNotNull(hssfRow.getCell(5)) && ObjectUtil.isNotNull(hssfRow.getCell(5).getStringCellValue())
                && hssfRow.getCell(5).getStringCellValue().equals("公司员工")) {
            String idLast = idNumber.substring(14);
            String loginName = userName + idLast;
            sysUser.setLoginName(loginName);
            //初始化密码
            sysUser.setPassword(SecureUtil.md5("123456"));
        }

        //记录创建时间
        sysUser.setCreateTime(new Date());

        return sysUser;
    }

    //将单元格中的日期字符串转为JAVA日期类型,支持2017/1/1，2017.1.1格式
    Date formateDate(String dateString) throws ParseException {
        Date date = new Date();

        if (dateString.length() < 6 || dateString.length() > 10) {
            return null;
        }

        //获取分隔符
        char separator = dateString.charAt(4);

        String format = null;

        int lastSepPlace = dateString.lastIndexOf(separator);
        if (lastSepPlace == 4) {
            //只有年月
            //月份是M还是MM
            if (dateString.charAt(5) == '0') {
                format = "yyyy" + separator + "MM";
            } else {
                format = "yyyy" + separator + "M";
            }
        } else if (lastSepPlace > 4 && lastSepPlace < 8) {
            //有年月日
            //月份是M还是MM
            if (dateString.charAt(5) == '0') {
                format = "yyyy" + separator + "MM";
            } else {
                format = "yyyy" + separator + "M";
            }
            //日是d还是dd
            if (dateString.charAt(dateString.length() - 2) == '0') {
                format = format + separator + "dd";
            } else {
                format = format + separator + "d";
            }
        } else {
            return null;
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat(format);


        date = sdf1.parse(dateString);
        return date;
    }

    //导出人员花名册
    public Result sysUserOutput(HttpServletResponse response, List<SysUser> sysUsers) {
        Result result = new Result();

        try {
            Map<String, Object> map = new HashMap<>();
            if (CollectionUtil.isEmpty(sysUsers)) {
                map.put("sysUsers", null);
            } else {
                map.put("sysUsers", sysUsers);
            }
            TemplateExportParams params = new TemplateExportParams(
                    "inoutPutTemplates/sysUserTemplet.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(2);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

//            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 12);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "人员花名册-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    public Result checkWxUserExist(String code) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("https://api.weixin.qq.com/sns/jscode2session");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("appid", this.APP_ID));
        params.add(new BasicNameValuePair("secret", this.APP_SECRET));
        params.add(new BasicNameValuePair("js_code", code));
        params.add(new BasicNameValuePair("grant_type", "authorization_code"));
        post.setEntity(new UrlEncodedFormEntity(params));
        CloseableHttpResponse response = httpClient.execute(post);
        HttpEntity entity = response.getEntity();
        String responseStr = EntityUtils.toString(entity);
        System.out.println(responseStr);
        JSONObject jsonObject= JSON.parseObject(responseStr);
        Result result = new Result();
        SysUser sysUser = sysUserMapper.findByOpenId(jsonObject.getString("openid"));
        if (ObjectUtil.isNull(sysUser)) {
            result.setFalse("还未进行账号绑定，请登录");
        } else {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getLoginName(), sysUser.getPassword());
            subject.login(token);
            SysUser sessionUser = (SysUser) subject.getSession().getAttribute("user");
            sessionUser.setSession_key(jsonObject.getString("session_key"));
            result.setData(sessionUser);
        }
        return result;
    }

    public Result bindWxUser(String loginName, String pwd, String openId) {
        Result result = new Result();
        SysUser sysUser = new SysUser();
        sysUser = sysUserMapper.find(loginName, SecureUtil.md5(pwd));
        if (sysUser == null) {
            result.setFalse("该用户不存在或密码错误");
        } else {
            sysUser.setOpenId(openId);
            sysUserMapper.updateByPrimaryKeySelective(sysUser);
            result.setMessage("绑定成功");
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getLoginName(), sysUser.getPassword());
            subject.login(token);
            SysUser sessionUser = (SysUser) subject.getSession().getAttribute("user");
            result.setData(sessionUser);
        }
        return result;
    }

    @Transactional
    public Result addEnterpriseUser(SysUser sysUser){
        Result result = new Result();

        sysUser.setCreateTime(new Date());
        sysUser.setPassword(SecureUtil.md5(sysUser.getPassword()));
        sysUser.setCompanyId(0);
        sysUserMapper.insertSelective(sysUser);
        if(CollectionUtil.isNotEmpty(sysUser.getAddRoleIds())){
            sysUser.getAddRoleIds().forEach(roleId->{
                SysUserRole userRole=new SysUserRole(roleId,sysUser.getUserId());
                userRoleMapper.insertSelective(userRole);
            });
        }
        return result;
    }

    @Transactional
    public Result updateEnterpriseUser(SysUser sysUser){
        Result result = new Result();
        sysUser.setCreateTime(new Date());
        sysUser.setPassword(null);
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        userRoleMapper.deleteByUserId(sysUser.getUserId());
        if(CollectionUtil.isNotEmpty(sysUser.getAddRoleIds())){
            sysUser.getAddRoleIds().forEach(roleId->{
                SysUserRole userRole=new SysUserRole(roleId,sysUser.getUserId());
                userRoleMapper.insertSelective(userRole);
            });
        }
        return result;
    }
    @Transactional
    public Result resetPwd(SysUser sysUser){
        Result result = new Result();
        String pwd=sysUser.getPassword();
        sysUser=sysUserMapper.selectByUserId(sysUser.getUserId());
        if(ObjectUtil.isNotNull(sysUser)){
            sysUser.setPassword(SecureUtil.md5(pwd));
            sysUserMapper.updateByPrimaryKeySelective(sysUser);
        }
        return result;
    }
}
